package com.upsuns.fileop;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.Selector;

import com.upsuns.entity.FileEntity;
import com.upsuns.multiop.ThreadBatch;
import com.upsuns.transfer.ServerTerminal;
import com.upsuns.utils.Constants;

/**
 *@Description:<p>文件写入线程</p>
 *@author 王旭
 *@time 2016-1-31 下午4:59:48
 */
public class FileWriterThread implements Runnable {
	
	private RandomAccessFile raf;
	
	private int flag; //线程标记
	
	private long start, len; //读取文件的范围
	
	private ServerTerminal server;
	
	public FileWriterThread(FileEntity fileEntity, long start, long len, int flag, Selector selector, Integer id) {
		this.start = start;
		this.len = len;
		this.flag = flag;
		try {
			this.raf = new RandomAccessFile(fileEntity.getFile(), "rw");
			raf.setLength(fileEntity.getFileSize());
		} catch (IOException e) {
			System.out.println("文件写入线程" + flag + "创建随机写入文件失败");
			e.printStackTrace();
		}
		
		server = new ServerTerminal(Constants.PORT_BASE + flag, selector, id);
	}
	
	@Override
	public void run() {
		
		try {
			server.receive(raf, start, len);
		} catch (IOException e) {
			System.out.println("文件写入线程" + flag + "写入文件失败");
			e.printStackTrace();
		}
		
		ThreadBatch.latch.countDown();
	}

}
